import {type Timestamp, TS} from "./Timestamp.ts";

export enum ItemType {
    //  "激活码"
    ACTIVATION_CODE = 1,
    //  "徽章"
    MEDAL = 2,
    //  "对人"
    TO_USER = 3,
    //  "未知"
    // UNKNOWN = 4,
    //  "对贴"
    TO_REPLY = 5,
}

export enum ItemStatus {
    // 徽章使用中
    MEDAL_USED = 8
}

// 对应关系
export const ItemTypes = [
    {label: "激活码", typeId: ItemType.ACTIVATION_CODE},
    {label: "徽章", typeId: ItemType.MEDAL},
    {label: "对人", typeId: ItemType.TO_USER},
    {label: "对贴", typeId: ItemType.TO_REPLY},
]

export interface ItemTypeInfo {
    type: ItemType
    subTypeId: number
    name: string
    description: string
    icon: string
    permission: string
    url: string
}

export const buildItemTypeInfo = (key: string, data: any): ItemTypeInfo => {
    const type = Number(key.split("_")[0]) as ItemType;
    const url = "https://img4.nga.178.com/ngabbs/" + (type == ItemType.MEDAL ?
        `medal/${data.icon}` :
        `nga_classic/items/${data.icon}`)
    return {
        type, url,
        subTypeId: Number(key.split("_")[1]),
        name: data.name,
        description: data.dscp?.replace("徽章注释:", "")?.trim(),
        icon: data.icon,
        permission: data.permission_buy_store,

    }
}

export const buildMedalInfo = (array: any[]): ItemTypeInfo => {
    return {
        type: ItemType.MEDAL,
        subTypeId: array[3],
        icon: array[0],
        name: array[1],
        description: array[2],
        permission: "",
        url: "https://img4.nga.178.com/ngabbs/medal/" + array[0]
    }
}

export interface ItemDataBody {
    data: ItemData[]
    page: number
    hasNext: boolean
}

export interface ItemData {
    id: number
    count: number
    type: ItemType
    subTypeId: number
    typeInfo: ItemTypeInfo | undefined
    time: Timestamp | undefined
    bits: number[]
}

export const buildItemDataBody = (data: any): ItemDataBody => {
    const typeInfoMap = new Map<string, ItemTypeInfo>()
    Object.keys(data.itemInfo).forEach(key => {
        typeInfoMap.set(key, buildItemTypeInfo(key, data.itemInfo[key]))
    })

    return {
        data: Object.values(data).filter((it: any) => it.id).map((item: any) => buildItemData(item, typeInfoMap)),
        page: data.currentPage,
        hasNext: !!data.morePage
    }
}

export const buildItemData = (data: any, typeInfoMap: Map<string, ItemTypeInfo>): ItemData => {
    const type = data.type as ItemType
    const subTypeId = data.sub_type as number
    const key = `${type}_${subTypeId}`
    const bits: number[] = []
    for (let i = 0; i < 32; i++) {
        if ((data.bit & Math.pow(2, i)) !== 0) {
            bits.push(i)
        }
    }
    return {
        id: data.id,
        count: data.count,
        type, subTypeId,
        typeInfo: typeInfoMap.get(key),
        time: TS(data.time),
        bits,
    }
}

